//
//  MQComposeView.swift
//  MQWeibo
//
//  Created by 毛强 on 16/1/4.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit
import pop

class MQComposeView: UIView {
    
    var target:UIViewController?
    var childMenuButtons:[UIButton] = [UIButton]()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func show(target:UIViewController){
        self.target = target
        self.target?.view.addSubview(self)
    }
    
    private func setupUI(){
        frame.size = CGSizeMake(SCREENW, SCREENH)
        
        // 获取一个磨砂的屏幕图片
        let imageView = UIImageView(image: UIImage.getScreenShot().applyLightEffect())
        
        // 添加控件
        addSubview(imageView)
        addSubview(sloganImage)
        
        // 添加约束
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self)
        }
        sloganImage.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.top.equalTo(self).offset(100)
        }
        
        addChildButton()
       
    }
    
    // 添加子按钮
    private func addChildButton(){
        
        
        let childButtonW: CGFloat = 80
        let childButtonH: CGFloat = 110
        // 每一个按钮之间的间距
        let childButtonMargin: CGFloat = (SCREENW - 3 * childButtonW) / 4
        
        
        // 读取 plist文件路径
        let path = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)!
        
        // 把 plist 文件转成 NSArray
        let composeButtonMenuInfos = NSArray(contentsOfFile: path)!
        
        for (i,value) in composeButtonMenuInfos.enumerate(){
            let button = MQComposeMenuButton()
            
            // 添加点击事件
            button.addTarget(self, action: "childButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
            
            // 设置数据
            let dict = value as! NSDictionary
            
            // 读取图片名字
            let iconName = dict["icon"]! as! String
            // 标题
            let title = dict["title"]! as! String
            button.setImage(UIImage(named: iconName), forState: UIControlState.Normal)
            button.setTitle(title, forState: UIControlState.Normal)
            
            // 取到当前遍历的按钮的第 xx 行和 第 xx 列
            let col = i % 3
            let row = i / 3
            // 计算位置
            let childButtonX = CGFloat(col + 1) * childButtonMargin + CGFloat(col) * childButtonW
            let childButotnY = (childButtonH + childButtonMargin) * CGFloat(row) + SCREENH
            // 设置 frame
            button.frame = CGRect(x: childButtonX, y: childButotnY, width: childButtonW, height: childButtonH)
            
            addSubview(button)
            
            childMenuButtons.append(button)
        }
    }
    
    @objc private func childButtonClick(button: UIButton) {
        
        // 将当前点击的按钮执行放大透明
        // 将没有点击的按钮执行缩小透明
        
        UIView.animateWithDuration(0.25, animations: { () -> Void in
            
            for value in self.childMenuButtons {
                
                value.alpha = 0.01
                
                if value == button {
                    // 放大
                    value.transform = CGAffineTransformMakeScale(2, 2)
                }else{
                    // 缩小
                    value.transform = CGAffineTransformMakeScale(0.2, 0.2)
                }
            }
            }) { (_) -> Void in
                
                // 怎么通过一个字符串初始化成一个对象
                // UIViewController
                
                if let type = NSClassFromString("MQWeibo.MQComposeViewController") as? UIViewController.Type {
                    let instance = type.init()
                    // 弹出控制器
                    self.target?.presentViewController(MQNavigationController(rootViewController: instance), animated: true, completion: { () -> Void in
                        self.removeFromSuperview()
                    })
                }
        }
    }

    
    // 当前控件被移动到 window 上的时候执行的方法
    override func didMoveToWindow() {
        // 让按钮从下往上执行动画
        for (index,button) in childMenuButtons.enumerate() {
            doAnimation(button, index: index, isUp: true)
        }
    }
    
    /// 执行动画
    ///
    /// - parameter button: 执行动画的按钮
    /// - parameter index:  按钮的索引
    /// - parameter isUp:   是执行向上动画还是向下
    private func doAnimation(button: UIButton, index: Int, isUp: Bool = false){
        // 执行动画
        let animation = POPSpringAnimation(propertyNamed: kPOPViewCenter)
        // toValue 接受对象类型，而 CGPoint 是一个结构体，所以我们需要将结构转成对象类型
        var y = button.center.y + 350
        if isUp {
            y = button.center.y - 350
        }
        
        animation.toValue = NSValue(CGPoint:CGPoint(x: button.center.x, y: y))
        
        // 弹性度：[0,20]，越大，幅度越大
        animation.springBounciness = 10
        // 弹性速度：[0,20] 越小，执行的时候时间越长
        animation.springSpeed = 8
        // CACurrentMediaTime() --> 当前系统的绝对时间
        animation.beginTime = CACurrentMediaTime() + Double(index) * 0.025
        button.pop_addAnimation(animation, forKey: nil)
    }

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        for (index,button) in childMenuButtons.reverse().enumerate(){
            doAnimation(button, index: index)
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.4 * Double(NSEC_PER_MSEC))), dispatch_get_main_queue()){
                self.removeFromSuperview()
        }
    }
    
      private lazy var sloganImage:UIImageView = UIImageView(image: UIImage(named: "compose_slogan"))
}


